//! 遥测模块，提供集成OpenTelemetry的功能
//!
//! 本模块允许接入OpenTelemetry来进行分布式跟踪和指标收集，
//! 支持对Actor系统的全面监控，包括消息传递、处理时间和错误率等。

pub mod metrics;
pub mod tracing;
#[cfg(feature = "opentelemetry")]
pub mod otel;

pub use self::metrics::{Metrics, Counter, Gauge, Histogram, Timer};
pub use self::tracing::{Tracer, Span, SpanContext, SpanStatus};
#[cfg(feature = "opentelemetry")]
pub use self::otel::{OtelTracer, OtelExporter, OtelConfig};

use std::time::{Duration, Instant};
use std::sync::Arc;
use crate::actor::{Actor, ActorContext, PID};

/// 遥测指标类型
#[derive(Debug, Clone)]
pub enum MetricType {
    /// 计数器类型指标
    Counter,
    /// 仪表盘类型指标
    Gauge,
    /// 直方图类型指标
    Histogram,
}

/// 遥测系统接口
pub trait TelemetrySystem: Send + Sync + 'static {
    /// 初始化遥测系统
    fn init(&self) -> Result<(), String>;
    
    /// 关闭遥测系统
    fn shutdown(&self) -> Result<(), String>;
    
    /// 创建计数器指标
    fn create_counter(&self, name: &str, description: &str, labels: &[&str]) -> Box<dyn Counter>;
    
    /// 创建仪表盘指标
    fn create_gauge(&self, name: &str, description: &str, labels: &[&str]) -> Box<dyn Gauge>;
    
    /// 创建直方图指标
    fn create_histogram(&self, name: &str, description: &str, labels: &[&str], buckets: &[f64]) -> Box<dyn Histogram>;
    
    /// 创建跟踪器
    fn tracer(&self) -> Box<dyn Tracer>;
}

/// 全局遥测系统
pub struct GlobalTelemetry {
    /// 内部系统实现
    system: Arc<dyn TelemetrySystem>,
}

impl GlobalTelemetry {
    /// 创建新的全局遥测系统
    pub fn new(system: Arc<dyn TelemetrySystem>) -> Self {
        Self { system }
    }
    
    /// 获取遥测系统
    pub fn system(&self) -> Arc<dyn TelemetrySystem> {
        self.system.clone()
    }
    
    /// 初始化遥测系统
    pub fn init(&self) -> Result<(), String> {
        self.system.init()
    }
    
    /// 关闭遥测系统
    pub fn shutdown(&self) -> Result<(), String> {
        self.system.shutdown()
    }
}

/// 遥测中间件，用于拦截Actor消息并记录指标
pub struct TelemetryMiddleware {
    /// 遥测系统
    telemetry: Arc<dyn TelemetrySystem>,
    /// 消息计数器
    message_counter: Box<dyn Counter>,
    /// 消息处理时间直方图
    message_duration: Box<dyn Histogram>,
    /// 错误计数器
    error_counter: Box<dyn Counter>,
}

impl TelemetryMiddleware {
    /// 创建新的遥测中间件
    pub fn new(telemetry: Arc<dyn TelemetrySystem>) -> Self {
        // 创建基本指标
        let message_counter = telemetry.create_counter(
            "protoactor_messages_total",
            "Total number of messages processed by actors",
            &["actor_type", "message_type"],
        );
        
        let message_duration = telemetry.create_histogram(
            "protoactor_message_duration_seconds",
            "Time taken to process messages",
            &["actor_type", "message_type"],
            &[0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0],
        );
        
        let error_counter = telemetry.create_counter(
            "protoactor_errors_total",
            "Total number of errors encountered during message processing",
            &["actor_type", "message_type", "error_type"],
        );
        
        Self {
            telemetry,
            message_counter,
            message_duration,
            error_counter,
        }
    }
    
    /// 记录消息处理
    pub fn record_message<A: Actor>(&self, actor_type: &str, message_type: &str) {
        self.message_counter.inc_with_labels(&[actor_type, message_type]);
    }
    
    /// 记录消息处理时间
    pub fn record_duration<A: Actor>(&self, actor_type: &str, message_type: &str, duration: Duration) {
        self.message_duration.record_with_labels(
            duration.as_secs_f64(),
            &[actor_type, message_type],
        );
    }
    
    /// 记录错误
    pub fn record_error<A: Actor>(&self, actor_type: &str, message_type: &str, error_type: &str) {
        self.error_counter.inc_with_labels(&[actor_type, message_type, error_type]);
    }
}

/// 获取当前系统性能指标
pub fn system_metrics() -> SystemMetrics {
    SystemMetrics {
        cpu_usage: get_cpu_usage(),
        memory_usage: get_memory_usage(),
        actor_count: get_actor_count(),
        mailbox_size: get_mailbox_size(),
    }
}

/// 系统性能指标
pub struct SystemMetrics {
    /// CPU使用率
    pub cpu_usage: f64,
    /// 内存使用量（字节）
    pub memory_usage: u64,
    /// Actor数量
    pub actor_count: usize,
    /// 邮箱大小平均值
    pub mailbox_size: f64,
}

// 私有辅助函数
fn get_cpu_usage() -> f64 {
    // TODO: 实现CPU使用率采集
    0.0
}

fn get_memory_usage() -> u64 {
    // TODO: 实现内存使用量采集
    0
}

fn get_actor_count() -> usize {
    // TODO: 实现Actor数量统计
    0
}

fn get_mailbox_size() -> f64 {
    // TODO: 实现邮箱大小统计
    0.0
}

/// 消息跟踪上下文
pub struct MessageTraceContext {
    /// 跟踪上下文
    pub context: SpanContext,
    /// 开始时间
    pub start_time: Instant,
    /// 消息类型
    pub message_type: String,
    /// 发送者
    pub sender: Option<PID>,
    /// 接收者
    pub receiver: PID,
}

impl MessageTraceContext {
    /// 创建新的消息跟踪上下文
    pub fn new(message_type: &str, sender: Option<&PID>, receiver: &PID, context: SpanContext) -> Self {
        Self {
            context,
            start_time: Instant::now(),
            message_type: message_type.to_string(),
            sender: sender.cloned(),
            receiver: receiver.clone(),
        }
    }
    
    /// 完成跟踪
    pub fn finish(self, tracer: &dyn Tracer) {
        let duration = Instant::now().duration_since(self.start_time);
        tracer.end_span(self.context, Some(duration));
    }
} 